package main

import (
	//基本路由 gin 框架中采用的路由库是 httprouter
	"github.com/gin-gonic/gin"
	"strconv"
	"gitee.com/winnie_gss/MessageBox/logs"
	"fmt"
	"encoding/json"
	"github.com/go-redis/redis"
)

func main() {

	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	logs.InitLog()
	initDb()
	InitRedis()

	//TODO : 首页
	r.GET("/article/selectall", func(c *gin.Context) {

		sort, err := strconv.Atoi(c.DefaultQuery("sort", "0"))
		logs.ErrorLog(err)

		var list []Article
		var value string

		value, err = RGet("list").Result()
		if err == redis.Nil {
			list = ArticleList(sort)
			listbyte, err := json.Marshal(list)
			logs.ErrorLog(err)
			RSet("list", string(listbyte))
			value, err = RGet("list").Result()
			logs.ErrorLog(err)
		}

		err = json.Unmarshal([]byte(value), &list)
		logs.ErrorLog(err)

		logs.InfoLog(fmt.Sprint("/article/selectall", c.Request.RemoteAddr, sort, list))

		c.JSON(200, gin.H{
			"sort": sort,
			"list": list,
		})
	})

	//TODO : 创建
	r.POST("/article/submitcreate", func(c *gin.Context) {
		title := c.PostForm("title")
		content := c.PostForm("content")

		flag := false
		id := InsertArticle(title, content)
		if id > 0 {
			flag = true
			RExpire("list", -1)
		}

		logs.InfoLog(fmt.Sprint("/article/submitcreate", c.Request.RemoteAddr, flag))

		c.JSON(200, gin.H{
			"status": flag,
		})
	})

	//TODO : 编辑
	r.GET("/article/editor", func(c *gin.Context) {
		id, err := strconv.Atoi(c.Query("id"))
		logs.ErrorLog(err)

		data := ViewArticleByEditor(id)

		logs.InfoLog(fmt.Sprint("/article/editor", c.Request.RemoteAddr, data))

		RExpire("list", -1)

		c.JSON(200, gin.H{
			"data": data,
		})
	})

	r.POST("/article/submiteditor", func(c *gin.Context) {
		id, err := strconv.Atoi(c.PostForm("id"))
		logs.ErrorLog(err)
		title := c.PostForm("title")
		content := c.PostForm("content")

		flag := false
		rows := UpdateArticle(id, title, content)

		if rows > 0 {
			flag = true
			RExpire("list", -1)
		}

		logs.InfoLog(fmt.Sprint("/article/submiteditor", c.Request.RemoteAddr, flag))

		c.JSON(200, gin.H{
			"status": flag,
		})
	})

	//TODO : 删除
	r.POST("article/delete", func(c *gin.Context) {
		id, err := strconv.Atoi(c.PostForm("id"))
		logs.ErrorLog(err)

		flag := false
		rows := DeleteArticle(id)

		if rows > 0 {
			flag = true
			RExpire("list", -1)
		}

		logs.InfoLog(fmt.Sprint("/article/delete", c.Request.RemoteAddr, flag))

		c.JSON(200, gin.H{
			"status": flag,
		})
	})

	//TODO : 详情
	r.GET("article/view", func(c *gin.Context) {
		id, err := strconv.Atoi(c.Query("id"))
		logs.SimplePanic(err)
		data := ViewArticle(id)

		logs.InfoLog(fmt.Sprint("/article/view", c.Request.RemoteAddr, data))

		c.JSON(200, gin.H{
			"data": data,
		})
	})

	//默认监听8080端口
	r.Run(":9002")
}
